/**
 * 
 */
package com.xth8013.as.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xth8013.as.dao.DataDictionaryDao;
import com.xth8013.as.dao.MenuDao;
import com.xth8013.as.dao.RoleDao;
import com.xth8013.as.dao.UserConfigParamDao;
import com.xth8013.as.dao.UserDao;
import com.xth8013.as.domain.DataDictionary;
import com.xth8013.as.domain.Menu;
import com.xth8013.as.domain.Role;
import com.xth8013.as.domain.User;
import com.xth8013.as.domain.UserConfigParam;
import com.xth8013.as.dto.UserMgrDTO;
import com.xth8013.as.exception.ServiceLogicException;
import com.xth8013.as.service.UserService;
import com.xth8013.as.util.MD5Util;
import com.xth8013.as.util.ObjectUtils;
import com.xth8013.as.util.RoleQueryHelper;
import com.xth8013.as.util.StringUtils;
import com.xth8013.as.util.UserQueryHelper;


/**
 * 
 * @Description:
 * @author: tianhua.xie
 * @Date: 2017年2月9日 下午9:53:07 
 * 
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private DataDictionaryDao dataDictionaryDao;
	@Autowired
	private UserConfigParamDao userConfigParamDao;

	@Override
	public int addUser(User user) {

		if (ObjectUtils.isBlank(user)) {
			throw new ServiceLogicException("账户信息不能为空");
		}

		user.setCreatedTime(new Date());
		user.setUserStatus("1");

		try {
			user.setUserPwd(MD5Util.md5Encode(user.getUserPwd()));
		} catch (Exception e) {
			throw new ServiceLogicException("系统错误");
		}

		return userDao.insert(user);
	}

	@Override
	public User getUserByAccount(String account) {
		if (StringUtils.isBlank(account)) {
			throw new ServiceLogicException("查询账户不能为空");
		}

		return userDao.selectByAccount(account);
	}


	@Override
	public Map<String, Object> getUserDataGrid(UserQueryHelper helper) {


		if (StringUtils.isBlank(helper.getOrderField()) || "userId".equals(helper.getOrderField())) {
			helper.setOrderField("user_id");
		} else if ("userAccount".equals(helper.getOrderField())) {
			helper.setOrderField("user_account");
		}

		Map<String, Object> dataMap = new HashMap<String, Object>();


		Integer total = userDao.cntUsersByHelper(helper);

		helper.setTotalRecNum(total);

		List<User> userList = userDao.loadAllUsersByHelper(helper);
		List<UserMgrDTO> userMgrDTOList = new ArrayList<UserMgrDTO>();
		for (User user : userList) {
			userMgrDTOList.add(UserMgrDTO.parseUserMgrDTo(user));
		}

		// System.out.println(userMgrDTOList);

		dataMap.put("total", total);
		dataMap.put("rows", userMgrDTOList);

		return dataMap;
	}

	@Override
	public List<Map<String, Object>> loadDepartmentList() {
		return this.loadDataDictionaryListByType(DataDictionary.TYPE_DEPARTMENT);
	}

	@Override
	public List<Map<String, Object>> loadJobTitleList() {
		return this.loadDataDictionaryListByType(DataDictionary.TYPE_JOBTITLE);
	}

	private List<Map<String, Object>> loadDataDictionaryListByType(String type) {
		/**
		 * [{ "id":1, "text":"text1" },{ "id":2, "text":"text2" },{ "id":3,
		 * "text":"text3", "selected":true },{ "id":4, "text":"text4" },{
		 * "id":5, "text":"text5" }]
		 */
		List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
		Map<String, Object> dataRow = null;

		List<DataDictionary> dataList = dataDictionaryDao.loadAlldatasByType(type);
		for (DataDictionary dataDictionary : dataList) {
			dataRow = new HashMap<String, Object>();
			dataRow.put("id", dataDictionary.getId());
			dataRow.put("text", dataDictionary.getItem());
			dataMapList.add(dataRow);
		}

		return dataMapList;
	}

	/**
	 * 若userId为空，则加载所有用户角色列表；否则，加载userId用户的所有用户角色列表
	 * 
	 */
	@Override
	public Map<String, Object> loadUserRoleList(Integer userId) {
		/**
		 * {"total":5,"rows":[
		 * {"productid":"FL-DSH-01","productname":"Manx","itemid":"EST-14"},
		 * {"selected":true,"productid":"FL-DSH-01","productname":"Manx","itemid":"EST-15"},
		 * {"productid":"FL-DLH-02","productname":"Persian","itemid":"EST-16"},
		 * {"productid":"FL-DLH-02","productname":"Persian","itemid":"EST-17"},
		 * {"productid":"AV-CB-01","productname":"AmazonParrot","itemid":"EST-18"}
		 * ]}
		 */
		
		// 用户角色列表
		Map<String, Object> dataMap = new HashMap<String, Object>();
		RoleQueryHelper helper = new RoleQueryHelper();
		helper.setQryRoleStatus("1");

		// 所有有效的角色总数
		Integer totalRecNum = roleDao.cntRolesByHelper(helper);
		helper.setTotalRecNum(totalRecNum);
		helper.setPageSize(totalRecNum);
		// 所有有效的角色列表信息
		List<Role> roleList = roleDao.loadAllRolesByHelper(helper);
		dataMap.put("total", totalRecNum);
		dataMap.put("rows", roleList);

		// 若userId为空，则加载所有用户角色列表；
		// 否则，加载userId用户的所有用户角色列表
		if (ObjectUtils.isNotBlank(userId)) {
			List<Integer> userRoleIdList = userDao.loadUserRoleByUserId(userId);
			// 用户拥有角色信息身份
			if (ObjectUtils.isNotBlank(userRoleIdList)) {
				// List<RoleDTO> roleDTOList = new ArrayList<RoleDTO>();
				// for (Role role : roleList) {
				// if (userRoleIdList.contains(role.getRoleId())) {
				// roleDTOList.add(RoleDTO.parseUserMgrDTo(role, true));
				// System.out.println(role);
				// } else {
				// roleDTOList.add(RoleDTO.parseUserMgrDTo(role));
				// }
				// }
				// dataMap.put("rows", roleDTOList);
				dataMap.put("userRoleIdList", userRoleIdList);
			}
		}

		return dataMap;
	}

	@Override
	public void save(User user, List<Integer> selectRoleIds) {

		if (ObjectUtils.isBlank(user) || StringUtils.isBlank(user.getUserAccount())) {
			throw new ServiceLogicException("用户账号不能为空");
		}

		Integer userId = null;

		User dbUser = userDao.selectByAccount(user.getUserAccount());

		// 已存在
		if (ObjectUtils.isNotBlank(dbUser)) {
			throw new ServiceLogicException("该用户账号【" + user.getUserAccount() + "】已存在");
		}

		user.setCreatedTime(new Date());
		user.setUserStatus("1");

		// 密码加密
		try {
			user.setUserPwd(MD5Util.md5Encode("888888"));
		} catch (Exception e) {
			throw new ServiceLogicException("系统错误");
		}

		// 添加角色信息
		// 插入信息 并 获取主键值
		userDao.insert(user);
		userId = user.getUserId();
		System.out.println("userId = " + userId);

		/**
		 * 插入到用户角色表
		 */
		if (ObjectUtils.isNotBlank(selectRoleIds)) {
			try {
				for (Integer roleId : selectRoleIds) {
					userDao.insertUserRole(userId, roleId);
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServiceLogicException("系统错误，用户角色创建失败");
			}
		}

	}

	@Override
	public User getUserById(Integer userId) {
		if (ObjectUtils.isBlank(userId)) {
			throw new ServiceLogicException("用户ID不能为空");
		}
		return userDao.selectById(userId);
	}

	@Override
	public void modifyUser(User user, List<Integer> selectRoleIds) {

		if (ObjectUtils.isBlank(user) || ObjectUtils.isBlank(user.getUserId())) {
			throw new ServiceLogicException("用户ID不能为空");
		}

		/**
		 * 修改用户信息
		 * 
		 */

		User dbUser = userDao.selectById(user.getUserId());
		if (ObjectUtils.isBlank(dbUser)) {
			throw new ServiceLogicException("该用户【" + user.getUserAccount() + "】不存在");
		}

		dbUser.setAddress(user.getAddress());
		dbUser.setEmail(user.getEmail());
		dbUser.setIdCardNo(user.getIdCardNo());
		dbUser.setMaritalStatus(user.getMaritalStatus());
		dbUser.setName(user.getName());
		dbUser.setNativePlace(user.getNativePlace());
		dbUser.setOfficeTel(user.getOfficeTel());
		dbUser.setPhone(user.getPhone());
		dbUser.setSex(user.getSex());
		dbUser.setDepartment(user.getDepartment());
		dbUser.setJobTitle(user.getJobTitle());

		try {
			userDao.update(dbUser);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceLogicException(e.getMessage());
		}

		/**
		 * 修改用户角色信息（删除所有，再新增）
		 * 
		 */
		userDao.deleteUserRolesByUserId(user.getUserId());

		if (ObjectUtils.isNotBlank(selectRoleIds)) {

			try {
				// 再新增
				userDao.insertUserRoles(user.getUserId(), selectRoleIds);

			} catch (Exception e) {
				e.printStackTrace();
				throw new ServiceLogicException("用户角色创建失败");
			}
		}

	}

	@Override
	public void delectUsers(String decUserIds) {

		if (StringUtils.isBlank(decUserIds)) {
			throw new ServiceLogicException("要删除的用户ID不能为空");
		}

		try {
			// 清除该用户在用户角色表的所有记录
			userDao.deleteUserRolesByIds(decUserIds);
			/**
			 * 伪删除
			 */
			userDao.deleteUsersByIds(decUserIds);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceLogicException("系统错误", e);
		}

	}

	@Override
	public List<Map<String, Object>> getUserMenuTreeDataById(Integer userId, String parentId) {

		if (ObjectUtils.isBlank(userId)) {
			throw new ServiceLogicException("用户ID不能为空");
		}
		List<Menu> userMenuList = null;
		List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
		Map<String, Object> treeNode = null;
		Map<String, Map<String, Object>> idNodeMap = new HashMap<String, Map<String, Object>>();

		try {
			userMenuList = menuDao.loadUserMenuTreeDataById(userId, parentId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		for (Menu menu : userMenuList) {
			treeNode = new HashMap<String, Object>();
			treeNode.put("id", menu.getMenuId());
			treeNode.put("text", menu.getMenuName());
			treeNode.put("menuHref", menu.getMenuHref());
			treeNode.put("menuTarget", menu.getMenuTarget());
			treeNode.put("parentId", menu.getParentId());

			treeNode.put("grade", menu.getGrade());
			treeNode.put("iconCls", "icon-nav");
			treeNode.put("isLeaf", menu.getIsLeaf());
			treeNode.put("isShow", menu.getIsShow());
			if (menu.getGrade() >= 3 && menu.getIsLeaf() == 0) {
				treeNode.put("state", "closed");
			}

			idNodeMap.put(menu.getMenuId() + "", treeNode);
			
			if (menu.getParentId()==0) {
				treeList.add(treeNode);
			} else {
				// 寻找父节点
				Map<String, Object> parenNode = idNodeMap.get(menu.getParentId()+"");
				if (parenNode != null) {
					List<Map<String, Object>> childList = null;
					if (parenNode.get("children") == null) {
						childList = new ArrayList<Map<String, Object>>();
					} else {
						childList = (List<Map<String, Object>>) parenNode.get("children");
					}
					childList.add(treeNode);
					parenNode.put("children", childList);
				}
			}
		
		}
		System.out.println(treeList);
		return treeList;
	}

	@Override
	public User modifyPersonalInfo(User user) {

		if (ObjectUtils.isBlank(user) || ObjectUtils.isBlank(user.getUserId())) {
			throw new ServiceLogicException("用户信息不能为空");
		}

		// 修改用户信息
		User dbUser = userDao.selectById(user.getUserId());

		if (ObjectUtils.isBlank(dbUser)) {
			throw new ServiceLogicException("该用户不存在");
		}

		dbUser.setAddress(user.getAddress());
		dbUser.setEmail(user.getEmail());
		dbUser.setIdCardNo(user.getIdCardNo());
		dbUser.setMaritalStatus(user.getMaritalStatus());
		dbUser.setName(user.getName());
		dbUser.setNativePlace(user.getNativePlace());
		dbUser.setOfficeTel(user.getOfficeTel());
		dbUser.setPhone(user.getPhone());
		dbUser.setSex(user.getSex());
		// dbUser.setDepartment(user.getDepartment());
		// dbUser.setJobTitle(user.getJobTitle());

		try {
			userDao.update(dbUser);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceLogicException(e.getMessage());
		}

		dbUser.setUserPwd("");

		return dbUser;
	}

	@Override
	public void modifyPersonalPwd(Integer userId, String newPwd, String oldPwd) {

		if (ObjectUtils.isBlank(userId)) {
			throw new ServiceLogicException("用户信息不能为空");
		}
		if (StringUtils.isBlank(newPwd)) {
			throw new ServiceLogicException("新密码不能为空");
		}
		if (StringUtils.isBlank(oldPwd)) {
			throw new ServiceLogicException("旧密码不能为空");
		}

		User dbUser = userDao.selectById(userId);

		if (ObjectUtils.isBlank(dbUser)) {
			throw new ServiceLogicException("该用户不存在");
		}

		/**
		 * 验证旧密码
		 */
		String md5Pwd = null;
		try {
			md5Pwd = MD5Util.md5Encode(oldPwd);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceLogicException("系统错误");
		}

		if (!md5Pwd.equals(dbUser.getUserPwd())) {
			throw new ServiceLogicException("旧密码不正确");
		}

		/**
		 * 修改密码
		 */
		try {
			md5Pwd = MD5Util.md5Encode(newPwd);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceLogicException("系统错误");
		}

		dbUser.setUserPwd(md5Pwd);
		userDao.update(dbUser);

	}

	@Override
	public void modifyConfigParam(UserConfigParam param) {

		if (ObjectUtils.isBlank(param) || ObjectUtils.isBlank(param.getParamId())) {
			throw new ServiceLogicException("参数配置不能为空");
		}

		UserConfigParam dbParam = userConfigParamDao.selectParamById(param.getParamId());

		if (ObjectUtils.isBlank(dbParam)) {
			userConfigParamDao.addConfigParam(param);
		} else {
			userConfigParamDao.updateConfigParam(param);
		}

	}

	@Override
	public UserConfigParam loadUserConfigParamById(Integer userId) {

		if (ObjectUtils.isBlank(userId)) {
			throw new ServiceLogicException("用户ID不能为空");
		}

		UserConfigParam param = userConfigParamDao.selectParamById(userId);

		// 若数据库不存在该用户的系统参数配置，则返回默认配置
		if (ObjectUtils.isBlank(param)) {
			param = new UserConfigParam();
			param.setParamId(userId);
		}

		return param;
	}

}
